<?php

namespace App\Jobs;

use App\Exceptions\Arr;
use App\Models\Appoint;
use App\Models\AppointNum;
use App\Models\Family;
use App\Models\FamilyChild;
use App\Models\HospitalImportChild;
use App\Models\HospitalUserFamily;
use App\Models\ImportFamily;
use App\Models\Notice;
use App\Models\TempPushRecord;
use App\Wechat\Temp;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Query\Builder;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\Middleware\WithoutOverlapping;
use Illuminate\Contracts\Queue\ShouldBeUniqueUntilProcessing;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Log;

class SyncDataChild implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $hospitalImportChild;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(HospitalImportChild $hospitalImportChild)
    {
        $this->hospitalImportChild=$hospitalImportChild;
        $this->onQueue('sync_data_child');
        $this->onConnection('redis');
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        try {
            $hospitalImportChild = $this->hospitalImportChild;
            $familyChildTable = app(FamilyChild::class)->getTable();
            $familyTable = app(Family::class)->getTable();
            $hospitalFamily = app(HospitalUserFamily::class)->getTable();

            $childs = Family::query()
                ->select(["{$familyTable}.id", "{$familyTable}.user_id"])
                ->join($familyChildTable, "{$familyChildTable}.family_id", '=', "{$familyTable}.id")
                ->join($hospitalFamily, "{$hospitalFamily}.family_id", '=', "{$familyTable}.id")
                ->where(function ($query) use ($hospitalImportChild,$familyTable) {
                    $query->where("{$familyTable}.name", $hospitalImportChild->field9)
                        ->orWhere("{$familyTable}.birthday", $hospitalImportChild->field12);
                })
                ->where("{$hospitalFamily}.hospital_id", $hospitalImportChild->hospital_id)
                //->where("{$hospitalFamily}.status", 1)
                ->where("{$familyChildTable}.mother", $hospitalImportChild->field39)
                //->where(DB::raw("SUBSTRING({$familyChildTable}.mother_idcard, -4)"), substr($hospitalImportChild->field42, -4))
                ->distinct()
                ->get();
            if($childs->isNotEmpty()) {
                foreach ($childs as $child) {
                    $row['family_id'] = $child->id;
                    $row['user_id'] = $child->user_id;
                    $row['hospital_id'] = $hospitalImportChild->hospital_id;
                    $row['import_id'] = $hospitalImportChild->id;
                    $row['type'] = 1;
                    $data[] = $row;
                }
                ImportFamily::query()->upsert($data, ['id']);
            }

        }catch(\Exception $e){


            $this->fail($e->getMessage());
        }
    }
    /**
     * 同一条数据同一时间只处理一次。
     *
     * @return array<int, object>
     */
    public function middleware(): array
    {
        return [(new WithoutOverlapping($this->hospitalImportChild->id))->dontRelease()];
    }
    /**
     * 获取作业的唯一 ID。
     */
    public function uniqueId(): string
    {
        return $this->hospitalImportChild->id;
    }
}
